package mspbots.cw.client.core.app;

import cn.hutool.core.date.LocalDateTimeUtil;
import lombok.Data;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.PastOrPresent;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * mspbots.cw.client.core.data.tickets.ManualSyncRequest
 *
 * @author <a href="https://github.com/vnobo">Alex bob</a>
 * @date Created by 2020/10/14
 */
@Data
@Validated
public class SyncRequest implements Serializable {

    @PastOrPresent(message = "Sync request param [beginTime] must be before the present date.")
    @NotNull(message = "Sync request param [beginTime] not null.")
    private LocalDateTime beginTime;

    @NotNull(message = "Sync request param [endTime] not null.")
    private LocalDateTime endTime;

    public static class SyncRequestValidator implements Validator {

        @Override
        public boolean supports(Class clazz) {
            return SyncRequest.class.equals(clazz);
        }

        @Override
        public void validate(Object obj, Errors errors) {
            if (errors.getErrorCount() == 0) {
                SyncRequest syncRequest = (SyncRequest) obj;
                if (LocalDateTimeUtil.between(syncRequest.getBeginTime(), syncRequest.getEndTime()).toDays() > 90) {
                    errors.reject("400", "The difference between the start time and the end " +
                            "time cannot be greater than 90 days");
                }
            }
        }
    }
}
